import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

public class FindSubstringInWraproundString {

    public static void main(String[] args) {
        FindSubstringInWraproundString findSubstringInWraproundString = new FindSubstringInWraproundString();
        System.out.println(findSubstringInWraproundString.findSubstringInWraproundString("abaab"));
    }

    Set<String> list = new HashSet<>();
    StringBuilder stringBuilder = new StringBuilder();

    public int findSubstringInWraproundString1(String p) {
        process(p, 0);
        return list.size();
    }

    public void process(String p, int i) {
        if (i == p.length()) {
            if (stringBuilder.length() != 0) {
                list.add(stringBuilder.toString());
            }
            return;
        }
        if (stringBuilder.length() != 0) {
            char c = stringBuilder.charAt(stringBuilder.length() - 1);
            char c1 = p.charAt(i);
            if ((c1 - c != 1 && c != 'z') || (c == 'z' && c - c1 != 25)) {
                process(p, i + 1);
            } else {
                process(p, i + 1);
                stringBuilder.append(p.charAt(i));
                process(p, i + 1);
                stringBuilder.deleteCharAt(stringBuilder.length() - 1);
            }
        } else {
            process(p, i + 1);
            stringBuilder.append(p.charAt(i));
            process(p, i + 1);
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        }
    }

    public int findSubstringInWraproundString2(String p) {
        int[] dp = new int[p.length()];
        char[] chars = p.toCharArray();
        HashMap<Character, Integer> map = new HashMap<>();
        int ans = 0;
        map.put(chars[0], 0);
        for (int i = 1; i < dp.length; i++) {
            if (chars[i] - chars[i - 1] == 1 || (chars[i] == 'a' && chars[i - 1] == 'z')) {
                dp[i] = dp[i - 1] + 1;
            }
            if (map.containsKey(chars[i])) {
                int index = map.get(chars[i]);
                if (dp[index] < dp[i]) {
                    ans -= dp[index];
                    ans += dp[i];
                    map.put(chars[i], i);
                }
                continue;
            }
            map.put(chars[i], i);
            ans += dp[i];
        }
        return ans + map.size();
    }

    public int findSubstringInWraproundString(String p) {
        int[] dp = new int[26];
        char[] chars = p.toCharArray();
        dp[chars[0] - 'a'] = 1;
        int temp = 1;
        for (int i = 1; i < chars.length; i++) {
            if (chars[i] - chars[i - 1] == 1 || (chars[i] == 'a' && chars[i - 1] == 'z')) {
                ++temp;
            } else temp = 1;
            dp[chars[i] - 'a'] = Math.max(dp[chars[i] - 'a'], temp);
        }
        return Arrays.stream(dp).sum();
    }
}
